<template>
  <section class="page-content">
    <div class="toolbar">
      <el-form :inline="true" :model="params">
        <el-form-item>
          <el-button type="success" size="small" icon="plus" @click="create">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData.data"
      @sort-change="sort"
      border
      style="width: 100%"
      max-height="100%">
      <el-table-column
        prop="id"
        sortable
        width="80"
        label="ID">
      </el-table-column>
      <el-table-column
        prop="name"
        sortable
        label="优惠券名称">
      </el-table-column>
      <el-table-column
        prop="send_type"
        sortable
        label="发放类型">
        <template slot-scope="scope">
          <span v-if="scope.row.send_type === 'LUCK_DRAW'">大转盘</span>
          <span v-else-if="scope.row.send_type === 'RECEIVE_FREE'">免费领取</span>
          <span v-else-if="scope.row.send_type === 'DAILY'">每日红包</span>
          <span v-else>{{scope.row.send_type}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="money"
        sortable
        label="面额">
      </el-table-column>
      <!-- <el-table-column
        prop="mini_consumption"
        sortable
        label="最低消费">
      </el-table-column> -->
      <el-table-column
        prop="total"
        sortable
        label="发放总量">
      </el-table-column>
      <el-table-column
        prop="sent_num"
        sortable
        label="已发放">
      </el-table-column>
      <el-table-column
        prop="used_num"
        sortable
        label="已使用">
      </el-table-column>
      <el-table-column
        label="使用期限">
        <template slot-scope="scope">
          <span v-if="scope.row.time_type === 'FIXED'">{{scope.row.end_use_at}}</span>
          <span v-else>+{{scope.row.time_scope}}天内有效</span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        width="180"
        label="操作">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editRow(scope.row)"
            type="default"
            size="small">
            编辑
          </el-button>
          <el-button
            @click.native.prevent="deleteRow(scope.row)"
            type="danger"
            size="small">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block toolbar">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="tableData.current_page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="parseInt(tableData.per_page)"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total">
      </el-pagination>
    </div>
    <!-- dialog -->
    <el-dialog class="dialog" title="添加优惠券" :visible.sync="visible">
      <el-form :model="formData" ref="formData" :rules="formRules"  label-width="120px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="formData.name" placeholder="优惠券名称"></el-input>
        </el-form-item>
        <el-form-item label="优惠券金额" prop="money">
          <el-input type="text" v-model="formData.money" placeholder="优惠券金额"></el-input>
        </el-form-item>
       <!--  <el-form-item label="最低消费" prop="mini_consumption">
          <el-input type="text" v-model="formData.mini_consumption" placeholder="最低消费"></el-input>
        </el-form-item> -->
        <el-form-item label="发放数量" prop="total">
          <el-input type="number" v-model.number="formData.total" placeholder="发放数量"></el-input>
        </el-form-item>
        <el-form-item label="发放方式" prop="send_type">
          <el-radio-group v-model="formData.send_type">
            <!-- <el-radio label="LUCK_DRAW">大转盘</el-radio>
            <el-radio label="RECEIVE_FREE">免费领取</el-radio> -->
            <el-radio label="DAILY">每日红包</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.send_type !== 'LUCK_DRAW'" label="开始发放时间" prop="start_send_at">
          <el-date-picker
            v-model="formData.start_send_at"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="formData.send_type !== 'LUCK_DRAW'"  label="结束发放时间" prop="end_send_at">
          <el-date-picker
            v-model="formData.end_send_at"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效期类型" prop="time_type">
          <el-radio-group v-model="formData.time_type">
            <el-radio label="FIXED">固定时间</el-radio>
            <el-radio label="SCOPE">自领取之日</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.time_type === 'FIXED'" label="起始使用时间" prop="start_use_at">
          <el-date-picker
            v-model="formData.start_use_at"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="formData.time_type === 'FIXED'" label="结束使用时间" prop="end_use_at">
          <el-date-picker
            v-model="formData.end_use_at"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="N天内有效" prop="time_scope" v-if="formData.time_type === 'SCOPE'">
          <el-radio-group v-model.number="formData.time_scope">
            <el-radio :label="7">7天</el-radio>
            <el-radio :label="30">30天</el-radio>
            <el-radio :label="180">180天</el-radio>
            <el-radio :label="365">365天</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用范围" prop="use_scope">
          <el-radio-group v-model="formData.use_scope">
            <el-radio label="ALL">全店通用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="formData.status">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle('formData')" :disabled="editLoading">取 消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleCreateOrEdit('formData')">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
  import {generateUrl} from '@/utils/helpers'
  export default {
    data () {
      return {
        loading: false,
        tableData: {
          first_page_url: '',
          from: '',
          to: '',
          last_page: '',
          last_page_url: '',
          next_page_url: '',
          prev_page_url: '',
          path: '',
          per_page: 0,
          total: 0,
          data: []
        },
        searchData: {
          title: ''
        },
        params: {
          order_by: 'id',
          order_type: 'desc',
          page_size: 20,
          title: '',
          page: 1
        },
        // dialog
        editLoading: false,
        visible: false,
        getDoodsLoading: false,
        goodsData: [],
        tempData: {
          id: null,
          name: '',
          money: '',
          mini_consumption: 0,
          total: 1000,
          send_type: 'DAILY',
          start_send_at: '',
          end_send_at: '',
          time_type: 'SCOPE',
          time_scope: 30,
          start_use_at: null,
          end_use_at: null,
          use_scope: 'ALL',
          status: true
        },
        formData: {},
        formRules: {
          name: [
            { required: true, message: '请输入名称', trigger: 'blur' },
            { min: 1, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
          ],
          money: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          mini_consumption: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          total: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          send_type: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          start_send_at: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          end_send_at: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          time_scope: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          time_type: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          start_use_at: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          end_use_at: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          use_scope: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ]
        }
      }
    },
    mounted () {
      this._restFormData()
      this._getData()
    },
    watch: {
      params: {
        deep: true,
        handler (newValue) {
          this._getData()
        }
      }
    },
    methods: {
      deleteRow (row) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.$http.delete('/coupons/' + row.id).then((response) => {
            this.loading = false
            this.$message.success('删除成功')
            this._getData()
          }).catch((error) => {
            this.loading = false
            console.log(error)
          })
        })
      },
      change (goodsName) {
        this.goodsData.forEach((el, index) => {
          if (el.name === goodsName) {
            this.formData.goods = el
            this.formData.share_img = el.thumb_img
            this.formData.goods_id = el.id
            this.formData.goods_name = el.name
            this.formData.share_desc = el.description
            this.formData.share_title = el.name
            this.formData.title = el.name
            this.formData.price = parseInt(el.price * 0.8)
          }
        })
      },
      cancle (formName) {
        this.$refs[formName].resetFields()
        this.visible = false
      },
      editRow (item) {
        this.formData = Object.assign({}, item)
        this.visible = true
      },
      onSubmit () {
        this.params.name = this.searchData.name
      },
      handleSizeChange (val) {
        this.params.page_size = val
      },
      handleCurrentChange (val) {
        this.params.page = val
      },
      sort (data) {
        let orderType = ''
        if (data.order === 'ascending') {
          orderType = 'asc'
        }
        if (data.order === 'descending') {
          orderType = 'desc'
        }
        this.params.order_type = orderType
        this.params.order_by = data.prop
      },
      create () {
        this._restFormData()
        this.visible = true
      },

      handleCreateOrEdit (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$http({
              method: this.formData.id === null ? 'post' : 'put',
              url: this.formData.id === null ? '/coupons' : '/coupons/' + this.formData.id,
              data: this.formData
            }).then((response) => {
              this.$message.success(response.data.message)
              this.editLoading = false
              this.visible = false
              this._getData()
            }).catch((error) => {
              this.editLoading = false
              console.log(error)
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      handleUploadSuccess (res, file) {
        console.log(res)
        this.formData.share_img = res
      },
      beforeUpload (file) {
        const isLt1M = file.size / 1024 / 1024 < 1
        if (!isLt1M) {
          this.$message.error('上传头像图片大小不能超过 1MB!')
        }
        return isLt1M
      },
      getGoods (keywords) {
        if (keywords !== '') {
          let url = '/goods?page_size=50&name=' + keywords
          this.getDoodsLoading = true
          this.$http.get(url).then((response) => {
            this.getDoodsLoading = false
            this.goodsData = response.data.data
          }).catch((error) => {
            this.loading = false
            console.log(error)
          })
        }
      },
      _restFormData () {
        this.formData = Object.assign({}, this.tempData)
      },
      _getData () {
        let url = generateUrl('/coupons', this.params)
        this.loading = true
        this.$http.get(url).then((response) => {
          this.loading = false
          this.tableData = response.data
        }).catch((error) => {
          this.loading = false
          console.log(error)
        })
      }
    }
  }
</script>
  
<style scoped>
  .el-select {
    width: 100%;
  }
  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100%; 
  }
</style>
